import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {SFComponent, SFSchema} from '@delon/form';
import {STData} from '@delon/abc/table/table.interfaces';
import {STColumn} from '@delon/abc';
import {BaseGridComponent, BaseService, Page, ReturnForm, ReturnPage} from '@sb/base';
import {NzMessageService} from 'ng-zorro-antd/message';
import {Observable} from 'rxjs';
import {OuUserSearchForm} from '../../../ou-user/entity/ou-user-search-form';
import {OuUserSelectAlainSchema} from '../../../ou-user/ou-user-select-alain/ou-user-select-alain.component';
import {OuUserService} from '../../../ou-user/ou-user.service';
import {OuOrgUserService} from '../../service/ou-org-user.service';
import {OuOrgUserSearchForm} from '../../entity/ou-org-user-search-form';
import {OuOrgUser} from '../../entity/ou-org-user';
import {OuOrgSearchConfig} from '../../entity/ou-org-search-config';
import {ActivatedRoute} from '@angular/router';

@Component({
    selector: 'ou-user-tab',
    templateUrl: './ou-user-tab.component.html',
    styleUrls: ['./ou-user-tab.component.less'],
    providers: [{
        provide: BaseService,
        useClass: OuOrgUserService
    }]
})
export class OuUserTabComponent implements OnInit {

    searchConfig: OuOrgSearchConfig = {
        searchUser: true,
        searchDept: true,
        searchSubOrg: true
    };

    showImportUserPanel = false;

    @ViewChild('baseGrid', {static: true})
    baseGrid: BaseGridComponent;

    @Output() itemClickEvent = new EventEmitter<any>();

    @ViewChild('sf', {static: false})
    sf: SFComponent;

    @Output() dataChange = new EventEmitter<any>();

    searchForm: OuUserSearchForm = {};
    loaded = false;
    typeIcon = {
        default: 'dr:user_yw'
    };
    columns: STColumn[] = [
        {
            title: '',
            type: 'checkbox',
            index: 'userId',
            width: '10%',
            className: 'text-center word-wrap'
        }, {
            title: '用户名',
            index: 'userName',
            width: '14%',
            className: 'text-center word-wrap'
        }, {
            title: '登录名',
            index: 'loginName',
            width: '14%',
            className: 'text-center word-wrap'
        }, {
            title: '性别',
            index: 'sex',
            format: (data: STData, col: STColumn) => {
                if (data.sex === 'boy') {
                    return '男';
                } else if (data.sex === 'girl') {
                    return '女';
                } else {
                    return '';
                }
            },
            width: '8%',
            className: 'text-center word-wrap'
        }, {
            title: '电话',
            index: 'tel',
            width: '14%',
            className: 'text-center word-wrap'
        }, {
            title: '状态',
            index: 'active',
            format: (data: STData, col: STColumn) => {
                return data.active ? '启用' : '停用';
            },
            width: '14%',
            className: 'text-center word-wrap'
        }
    ];
    schema: SFSchema = {
        properties: {
            userName: {
                type: 'string',
                title: '用户名称',
                minLength: 2
            },
            loginName: {
                type: 'string',
                title: '登录名称',
                minLength: 2
            },
            tel: {
                type: 'string',
                title: '联系电话',
                format: 'regex',
                pattern: '^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\\d{8})$',
                ui: {
                    errors: {pattern: '请输入有效的电话号码'}
                }
            },
            positionId: {
                type: 'string',
                title: '所属岗位',
                ui: {
                    widget: 'ou-position-select-alain'
                } as OuUserSelectAlainSchema,
            },
            sex: {
                type: 'string',
                title: '用户性别',
                enum: [{
                    value: 'boy',
                    label: '男'
                }, {
                    value: 'girl',
                    label: '女'
                }],
                ui: {
                    widget: 'radio'
                },
                default: 'boy'
            },
            // officeTel: {
            //     type: 'string',
            //     title: '办公电话'
            // },
            // email: {
            //     type: 'string',
            //     title: '电子邮箱',
            //     format: 'email'
            // },
            // wechat: {
            //     type: 'string',
            //     title: '微 信 号'
            // },
            // qq: {
            //     type: 'string',
            //     title: 'Q Q号码'
            // },
            //
            // endDate: {
            //     type: 'string',
            //     title: '失效日期',
            //     format: 'date-time'
            // },
            active: {
                type: 'boolean',
                title: '状态',
                ui: {
                    checkedChildren: '启用',
                    unCheckedChildren: '停用'
                },
                default: true
            },
        },
        required: ['userName', 'loginName']
    } as SFSchema;
    importSchema: SFSchema = {
        properties: {
            positionId: {
                type: 'string',
                title: '所属岗位',
                ui: {
                    widget: 'ou-position-select-alain'
                } as OuUserSelectAlainSchema,
            },
            userIds: {
                type: 'string',
                title: '选择用户',
                ui: {
                    widget: 'ou-user-select-alain',
                    valueType: 'array',
                    multiple: true,
                } as OuUserSelectAlainSchema
            }
        },
        required: ['userIds']
    } as SFSchema;

    constructor(
        private ouUserService: OuUserService,
        private message: NzMessageService,
        private ouOrgUserService: OuOrgUserService) {
    }

    _orgId: string;

    @Input()
    set orgId(_orgId: string) {
        this._orgId = _orgId;
        if (_orgId) {
            this.searchForm.orgId = _orgId;
            if (this.loaded) {
                this.baseGrid.reload();
            }
            this.loaded = true;
        }
    }

    ngOnInit() {
    }

    recordWrapper(value) {
        return value;
    }

    afterDetailInit(sf: SFComponent): void {
        sf.getProperty('/tel').valueChanges.subscribe((v) => {
            if (this.baseGrid.detailPanelType === 'add') {
                const loginNameProperty = sf.getProperty('/loginName');
                loginNameProperty.setValue(v, true);
            }
        });
    }

    customLoadPageMethod(searchForm: OuOrgUserSearchForm, baseService?: BaseService<STData, Page>): Observable<ReturnForm<ReturnPage<OuOrgUser>>> {
        return this.ouOrgUserService.listWithUserDetail(searchForm);
    }

    customCommitMethod(form: OuOrgUser, baseService?: BaseService<STData, Page>): Observable<ReturnForm<any>> {
        form.orgId = this._orgId;
        return this.ouOrgUserService.commit(form);
    }

    customRemoveMethod(data: OuOrgUser[], baseService?: BaseService<STData, Page>) {
        return this.ouOrgUserService.remove(data.map(v => v.id));
    }

    resetPassword() {
        const ids = this.baseGrid.checkData.map(v => v.id);
        this.ouOrgUserService.resetPassword(ids).subscribe(
            res => {
                if (res.success) {
                    this.message.success('密码重置成功');
                } else {
                    this.message.error('重置密码错误：' + res.errorMessage);
                }
            }
        );
    }

    unlockPassword() {
        const ids = this.baseGrid.checkData.map(v => v.id);
        this.ouOrgUserService.unlockPassword(ids).subscribe(
            res => {
                if (res.success) {
                    this.message.success('解锁成功');
                } else {
                    this.message.error('解锁不成功！');
                }
            }
        );
    }


    dataReload() {
        this.dataChange.emit();
    }

    importUsers() {
        const value = this.sf.value;
        this.ouOrgUserService.commitMulti(value.userIds, this._orgId, value.positionId).subscribe(
            res => {
                if (res.success) {
                    this.message.success('用户导入成功');
                    this.baseGrid.reload();
                    this.showImportUserPanel = false;
                    this.dataChange.emit();
                } else {
                    this.message.success('用户导入失败');
                }
            }
        );
    }

    itemClick(user: STData) {
        const ouOrgUser = user as OuOrgUser;
        this.itemClickEvent.emit(ouOrgUser.userId);
    }

}
